package com.luyi.sensor.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * DruidConfig
 * author: luyi
 * time: 2022/1/7 20:33
 */
@Configuration
public class DruidConfig {
  @Resource
  private JdbcParamConfig jdbcParamConfig ;
  @Resource
  private DruidProperties druidProperties ;

  @Bean
  public DataSource dataSource(){
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(jdbcParamConfig.getUrl());
    datasource.setDriverClassName(jdbcParamConfig.getDriverClassName());
    datasource.setUsername(jdbcParamConfig.getUserName());
    datasource.setPassword(jdbcParamConfig.getPassword());

    System.out.println(jdbcParamConfig.toString());

    //configuration
    datasource.setInitialSize(druidProperties.getInitialSize());
    System.out.println(druidProperties.toString());
    datasource.setMinIdle(druidProperties.getMinIdle());
    datasource.setMaxActive(druidProperties.getMaxActive());
    datasource.setMaxWait(druidProperties.getMaxWait());

    datasource.setTimeBetweenEvictionRunsMillis(druidProperties.getTimeBetweenEvictionRunsMillis());
    datasource.setMinEvictableIdleTimeMillis(druidProperties.getMinEvictableIdleTimeMillis());
    datasource.setTestWhileIdle(druidProperties.isTestWhileIdle());

    datasource.setPoolPreparedStatements(druidProperties.isPoolPreparedStatements());
    datasource.setMaxPoolPreparedStatementPerConnectionSize(druidProperties.getMaxPoolPreparedStatementPerConnectionSize());

    datasource.setConnectionErrorRetryAttempts(druidProperties.getConnectionErrorRetryAttempts());
    datasource.setBreakAfterAcquireFailure(druidProperties.isBreakAfterAcquireFailure());
    datasource.setTimeBetweenConnectErrorMillis(druidProperties.getTimeBetweenConnectErrorMillis());
    datasource.setValidationQuery(druidProperties.getValidationQuery());
    return datasource;
  }

  @Bean
  public SqlSessionFactory clickHouseSqlSessionFactoryBean() throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource());
    // 实体 model的 路径
    factory.setTypeAliasesPackage("com.luyi.sensor.entity");
    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    factory.setMapperLocations(resolver.getResources("classpath:com/luyi/sensor/dao/*/*.xml"));
    //开启驼峰命名转换
    factory.getObject().getConfiguration().setMapUnderscoreToCamelCase(false);
    return factory.getObject();
  }
}
